/**
 * 上传控制器
 * 处理文件上传和OCR识别
 */

import * as ocrService from '../services/ocrService.js';
import { AppError } from '../utils/appError.js';

/**
 * 上传图片并进行OCR识别
 * POST /api/v1/upload/ocr
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 * @param {Function} next - Express next函数
 */
export const uploadAndRecognize = async (req, res, next) => {
  try {
    // 1. 验证文件是否上传
    if (!req.file) {
      throw new AppError('NO_FILE', '请上传图片文件', 400);
    }

    // 2. 获取文件buffer
    const imageBuffer = req.file.buffer;
    const originalName = req.file.originalname;
    const fileSize = req.file.size;

    console.log(`开始处理上传的图片: ${originalName} (${(fileSize / 1024).toFixed(2)}KB)`);

    // 3. 调用OCR服务识别文字
    const ocrResult = await ocrService.recognizeText(imageBuffer);

    // 4. 清理内存（虽然会自动垃圾回收，但显式清理更好）
    req.file.buffer = null;

    // 5. 返回识别结果
    res.status(200).json({
      success: true,
      data: {
        text: ocrResult.data.text,
        rawText: ocrResult.data.rawText,
        confidence: ocrResult.data.confidence,
        questionableSections: ocrResult.data.questionableSections,
        metadata: {
          ...ocrResult.data.metadata,
          originalFileName: originalName,
          uploadedBy: req.user.id,
          uploadedAt: new Date().toISOString(),
        },
      },
      message: '图片识别成功',
    });
  } catch (error) {
    // 清理内存
    if (req.file && req.file.buffer) {
      req.file.buffer = null;
    }

    // 传递错误给错误处理中间件
    next(error);
  }
};

/**
 * 上传多张图片并进行批量OCR识别
 * POST /api/v1/upload/ocr/batch
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 * @param {Function} next - Express next函数
 */
export const uploadAndRecognizeMultiple = async (req, res, next) => {
  try {
    // 1. 验证文件是否上传
    if (!req.files || req.files.length === 0) {
      throw new AppError('NO_FILES', '请上传至少一张图片', 400);
    }

    // 2. 提取所有文件的buffer
    const imageBuffers = req.files.map((file) => file.buffer);
    const fileNames = req.files.map((file) => file.originalname);

    console.log(`开始批量处理${req.files.length}张图片`);

    // 3. 调用OCR服务批量识别
    const batchResult = await ocrService.recognizeMultiple(imageBuffers);

    // 4. 清理内存
    req.files.forEach((file) => {
      file.buffer = null;
    });

    // 5. 组装结果（添加文件名信息）
    const results = batchResult.data.map((result, index) => {
      if (result.success) {
        return {
          success: true,
          fileName: fileNames[index],
          data: {
            text: result.data.text,
            confidence: result.data.confidence,
          },
        };
      } else {
        return {
          success: false,
          fileName: fileNames[index],
          error: result.error,
        };
      }
    });

    // 6. 返回批量识别结果
    res.status(200).json({
      success: true,
      data: {
        total: results.length,
        successful: results.filter((r) => r.success).length,
        failed: results.filter((r) => !r.success).length,
        results: results,
      },
      message: batchResult.message,
    });
  } catch (error) {
    // 清理内存
    if (req.files) {
      req.files.forEach((file) => {
        if (file && file.buffer) {
          file.buffer = null;
        }
      });
    }

    // 传递错误给错误处理中间件
    next(error);
  }
};

